package gscore

import (
	"context"

	"gitee.com/crack007/goose/gsutil"
	"github.com/spf13/cobra"
)

type BaseBuilder struct {
	FlagCallbackList []FlagCallback
	CobraCmd         *cobra.Command
	PprofPort        uint16
	LogDebug         bool
	LogTrace         bool
	ConfigPath       string
	Ctx              context.Context
	CancelFunc       context.CancelFunc
	ConfigObject     any
}

func (x *BaseBuilder) GetCtx() context.Context {
	return x.Ctx
}

func (x *BaseBuilder) GetCancelFunc() context.CancelFunc {
	return x.CancelFunc
}

func (x *BaseBuilder) SetCobraCmd(cobraCmd *cobra.Command) {
	x.CobraCmd = cobraCmd
}

func (x *BaseBuilder) GetLogDebug() bool {
	return x.LogDebug
}

func (x *BaseBuilder) GetLogTrace() bool {
	return x.LogTrace
}

func (x *BaseBuilder) GetConfigPath() string {
	return x.ConfigPath
}

func (x *BaseBuilder) GetCobraCmd() *cobra.Command {
	return x.CobraCmd
}

func (x *BaseBuilder) RegisterFlag(flagCallback FlagCallback) {
	x.FlagCallbackList = append(x.FlagCallbackList, flagCallback)
}

func (x *BaseBuilder) EnableDebugFlag() *BaseBuilder {
	x.CobraCmd.PersistentFlags().BoolVar(&x.LogDebug, "v", false, "log level debug")
	x.CobraCmd.PersistentFlags().BoolVar(&x.LogTrace, "vv", false, "log level trace")
	return x
}

// 开启应用配置。
//   - @defaultConfigPath 配置路径，如果传空值，则使用程序所在路径的 config.yml 配置。
func (x *BaseBuilder) EnableConfigFlag(defaultConfigPath string, configObject any) *BaseBuilder {
	if defaultConfigPath == "" {
		defaultConfigPath = gsutil.RuntimeUtil.GetExecPath() + "/config.yml"
	}

	if configObject == nil {
		configObject = &DefaultConfig
	}

	x.ConfigObject = configObject
	x.CobraCmd.PersistentFlags().StringVar(&x.ConfigPath, "config", defaultConfigPath, "config.yml 配置路径")
	return x
}

func (x *BaseBuilder) PreFlags() {
	for _, flagCallback := range x.FlagCallbackList {
		flagCallback(x.CobraCmd)
	}

	// 避免重复注册flag
	x.FlagCallbackList = nil
}
